package com.yingpai.fitness.dvp_2_0.main.activity.mine;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.main.activity.fitness.CourseDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.activity.fitness.PersonalDetailActivity;
import com.yingpai.fitness.dvp_2_0.common.activity.CommonActivity;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.IsSuccessBean;
import com.yingpai.fitness.entity.MyClassBean;
import com.yingpai.fitness.entity.wx.TokenBean;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by ASUS on 2018/6/5.
 */

public class MyClassActivity extends CommonActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    private int pageNum = 1;
    private int pageSize = 10;
    private QuickAdapter<MyClassBean.MapData.PageInfoData.ListData> quickAdapter;
    private TokenBean tokenBean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusFlag(Contacts.NORMAL_STATUS);
        setContentView(R.layout.dvp_2_0_activity_my_class);
    }

    @Override
    protected void initView() {
        setTitle("我的私教课/操课");
        tokenBean = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);
        refreshLayout.setOnRefreshLoadMoreListener(this);

        quickAdapter = new QuickAdapter<MyClassBean.MapData.PageInfoData.ListData>(this, R.layout.item_class) {
            @Override
            protected void convert(BaseAdapterHelper helper, final MyClassBean.MapData.PageInfoData.ListData item) {

                ImageView photo = helper.getView(R.id.photo);
                Glide.with(context)
                        .load(item.getPhoto_urls())
                        .centerCrop()
                        .placeholder(R.mipmap.default_small_bg)
                        .into(photo);

                helper.setText(R.id.address, item.getStore_name());

                LinearLayout timeLl = helper.getView(R.id.time_ll);
                if (item.getCurriculum_category_id() == 7) {
                    timeLl.setVisibility(View.VISIBLE);
                    helper.setText(R.id.time, item.getStart_time().substring(5) + "-" + item.getEnd_time().substring(item.getEnd_time().indexOf(" ") + 1));
                    helper.setText(R.id.title, item.getName());
                } else if (item.getCurriculum_category_id() == 8) {
                    timeLl.setVisibility(View.INVISIBLE);
                    helper.setText(R.id.title, item.getCoachName());
                }

                ImageView is_use = helper.getView(R.id.is_use);

                if (Constant.REQUEST_SUCCESS_0.equals(item.getStatus())) {
                    is_use.setImageResource(R.mipmap.no_use);
                    is_use.setClickable(true);
                    is_use.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MyClassActivity.this);
                            builder.setTitle("温馨提示");
                            builder.setMessage("确认使用该课程吗?");
                            builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(final DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                    showDialog(MyClassActivity.this, null);
                                    HttpParams params = new HttpParams();
                                    params.put("orderId", item.getId());
                                    finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.USE_CURRICULUMN, params, Url.USE_CURRICULUMN, new Callback<IsSuccessBean>() {
                                        @Override
                                        public void onSuccess(IsSuccessBean isSuccessBean) {
                                            if (isSuccessBean.getCode().equals(Constant.REQUEST_SUCCESS_0000)) {
                                                item.setStatus("1");
                                            } else {
                                                item.setStatus("0");
                                            }
                                            quickAdapter.notifyDataSetChanged();
                                            dismissDialog();
                                        }

                                        @Override
                                        public void onError(Response<String> response) {
                                            super.onError(response);
                                            item.setStatus("0");
                                            dismissDialog();
                                        }
                                    });

                                }
                            });
                            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                            //参数都设置完成了，创建并显示出来
                            builder.create().show();
                        }
                    });
                } else if (item.getStatus().equals("1")) {
                    is_use.setImageResource(R.mipmap.used);
                    is_use.setClickable(false);
                }
//                helper.setText(R.id.price,"￥"+item.getTotalPrice()+"RMB");
            }
        };
        listview.setAdapter(quickAdapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (quickAdapter.getItem(position).getCurriculum_category_id() == 7) {
                    Bundle bundle = new Bundle();
                    bundle.putInt("courseId", quickAdapter.getItem(position).getCurriculum_id());
                    bundle.putInt("storeId", quickAdapter.getItem(position).getSubsidiary_organ());
                    startActivity(CourseDetailActivity.class, bundle);
                } else {
                    Bundle bundle = new Bundle();
                    bundle.putInt("courseId", quickAdapter.getItem(position).getCurriculum_id());
                    bundle.putInt("storeId", quickAdapter.getItem(position).getSubsidiary_organ());
                    startActivity(PersonalDetailActivity.class, bundle);
                }
            }
        });
    }

    @Override
    protected void initData() {
        pageNum = 1;
        requestData();
    }

    private void requestData() {
        showDialog(this, null);
        HttpParams params = new HttpParams();
        params.put("customerId", tokenBean.getId());
        params.put("pageNum", pageNum++);
        params.put("pageSize", pageSize);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_MY_CURRICULUM, params, Url.GET_MY_CURRICULUM, new Callback<MyClassBean>() {
            @Override
            public void onSuccess(MyClassBean myClassBean) {
                if (myClassBean.getResult().equals(Constant.REQUEST_SUCCESS)) {
                    if (pageNum - 1 == 1) {
                        if (myClassBean.getMap().getPageInfo().getTotal() > 0) {
                            empty.setVisibility(View.GONE);
                            quickAdapter.clear();
                            quickAdapter.addAll(myClassBean.getMap().getPageInfo().getList());
                        } else {
                            empty.setVisibility(View.VISIBLE);
                        }

                    } else {
                        quickAdapter.addAll(myClassBean.getMap().getPageInfo().getList());
                    }

                    int pagecount;
                    if (myClassBean.getMap().getPageInfo().getTotal() % pageSize == 0) {
                        pagecount = myClassBean.getMap().getPageInfo().getTotal() / pageSize;
                    } else {
                        pagecount = myClassBean.getMap().getPageInfo().getTotal() / pageSize + 1;
                    }

                    if (pageNum > pagecount) {
                        refreshLayout.setNoMoreData(true);
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.setNoMoreData(false);
                    }

                    refreshLayout.finishRefresh();
                    refreshLayout.finishLoadMore();
                    quickAdapter.notifyDataSetChanged();
                } else {
                    if (pageNum - 1 == 1) {
                        empty.setVisibility(View.VISIBLE);
                    } else {
                        empty.setVisibility(View.GONE);
                    }
                    showToast(myClassBean.getMsg());
                }
                dismissDialog();
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                if (pageNum - 1 == 1) {
                    empty.setVisibility(View.VISIBLE);
                } else {
                    empty.setVisibility(View.GONE);
                }
                dismissDialog();
            }
        });
    }

    @Override
    @OnClick({})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {

        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        requestData();
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        requestData();
    }
}
